<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/Frog_32px_1177822_easyicon.net.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/Frog_16px_1177822_easyicon.net.ico">
  <link rel="mask-icon" href="/images/Frog_32px_1177822_easyicon.net.ico" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">
  <link rel="stylesheet" href="/lib/pace/pace-theme-minimal.min.css">
  <script src="/lib/pace/pace.min.js"></script>

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"hxy1997.xyz","root":"/","scheme":"Pisces","version":"7.8.0","exturl":false,"sidebar":{"position":"left","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":"valine","storage":true,"lazyload":true,"nav":null,"activeClass":"valine"},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"输入关键字","hits_empty":"没有找到与「${query}」相关搜索","hits_stats":"${hits} 条相关记录，共耗时 ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.json"};
  </script>

  <meta name="description" content="懒加载等到用户滚动页面，当图片滚动到视区时才发出对应的网络请求，达到节省带宽的目的，使得网页加载更快。其实懒加载有很常规的实现方案，先通过data-src存放真正需要显示的图片路径，而img自带的src放一张占位图片。监听鼠标滚动事件，通过 el.getBoundingClientRect() 获取到当前元素与视口的位置关系，确定图片是否加载。在加载完成之后为了性能考虑，删除 data-src ，">
<meta property="og:type" content="article">
<meta property="og:title" content="IntersectionObserver实现懒加载">
<meta property="og:url" content="https://hxy1997.xyz/2021/04/01/IntersectionObserver%E5%AE%9E%E7%8E%B0%E6%87%92%E5%8A%A0%E8%BD%BD/index.html">
<meta property="og:site_name" content="hxy的博客">
<meta property="og:description" content="懒加载等到用户滚动页面，当图片滚动到视区时才发出对应的网络请求，达到节省带宽的目的，使得网页加载更快。其实懒加载有很常规的实现方案，先通过data-src存放真正需要显示的图片路径，而img自带的src放一张占位图片。监听鼠标滚动事件，通过 el.getBoundingClientRect() 获取到当前元素与视口的位置关系，确定图片是否加载。在加载完成之后为了性能考虑，删除 data-src ，">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203027.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203034.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203043.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203055.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203105.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203114.webp">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203122.webp">
<meta property="article:published_time" content="2021-04-01T12:40:00.000Z">
<meta property="article:modified_time" content="2021-04-18T12:31:35.579Z">
<meta property="article:author" content="hxy">
<meta property="article:tag" content="JavaScript">
<meta property="article:tag" content="懒加载">
<meta property="article:tag" content="IntersectionObserver">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203027.webp">

<link rel="canonical" href="https://hxy1997.xyz/2021/04/01/IntersectionObserver%E5%AE%9E%E7%8E%B0%E6%87%92%E5%8A%A0%E8%BD%BD/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>IntersectionObserver实现懒加载 | hxy的博客</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

<link rel="alternate" href="/atom.xml" title="hxy的博客" type="application/atom+xml">
</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">hxy的博客</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">Mia san Mia!</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/huxingyi1997" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://hxy1997.xyz/2021/04/01/IntersectionObserver%E5%AE%9E%E7%8E%B0%E6%87%92%E5%8A%A0%E8%BD%BD/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/Robben.gif">
      <meta itemprop="name" content="hxy">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="hxy的博客">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          IntersectionObserver实现懒加载
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2021-04-01 20:40:00" itemprop="dateCreated datePublished" datetime="2021-04-01T20:40:00+08:00">2021-04-01</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2021-04-18 20:31:35" itemprop="dateModified" datetime="2021-04-18T20:31:35+08:00">2021-04-18</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/web%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">web前端</span></a>
                </span>
            </span>

          
            <span class="post-meta-item" title="热度" id="busuanzi_container_page_pv" style="display: none;">
              <span class="post-meta-item-icon">
                <i class="fa fa-eye"></i>
              </span>
              <span class="post-meta-item-text">热度：</span>
              <span id="busuanzi_value_page_pv"></span>
            </span>
  
  <span class="post-meta-item">
    
      <span class="post-meta-item-icon">
        <i class="far fa-comment"></i>
      </span>
      <span class="post-meta-item-text">Valine：</span>
    
    <a title="valine" href="/2021/04/01/IntersectionObserver%E5%AE%9E%E7%8E%B0%E6%87%92%E5%8A%A0%E8%BD%BD/#valine-comments" itemprop="discussionUrl">
      <span class="post-comments-count valine-comment-count" data-xid="/2021/04/01/IntersectionObserver%E5%AE%9E%E7%8E%B0%E6%87%92%E5%8A%A0%E8%BD%BD/" itemprop="commentCount"></span>
    </a>
  </span>
  
  

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>懒加载等到用户滚动页面，当图片滚动到视区时才发出对应的网络请求，达到节省带宽的目的，使得网页加载更快。其实懒加载有很常规的实现方案，先通过data-src存放真正需要显示的图片路径，而img自带的src放一张占位图片。监听鼠标滚动事件，通过 <code>el.getBoundingClientRect()</code> 获取到当前元素与视口的位置关系，确定图片是否加载。在加载完成之后为了性能考虑，删除 <code>data-src</code> ，这样就可以避免重复的图片加载，其中要注意 <code>getBoundingClientRect</code> 会触发浏览器的回流。IntersectionObserver是个还在草案中的API，不过大部分浏览器均已实现（除了我大IE），适用该API也能实现上述的懒加载功能。</p>
<span id="more"></span>

<h1 id="1-IntersectionObserver是什么"><a href="#1-IntersectionObserver是什么" class="headerlink" title="1.IntersectionObserver是什么"></a>1.IntersectionObserver是什么</h1><h2 id="1-1-概念"><a href="#1-1-概念" class="headerlink" title="1.1 概念"></a>1.1 概念</h2><blockquote>
<p>IntersectionObserver接口(从属于Intersection Observer API)为开发者提供了一种可以异步监听目标元素与其祖先或视窗(viewport)交叉状态的手段。祖先元素与视窗(viewport)被称为根(root)。</p>
</blockquote>
<p>这是MDN上给的官方概念，不用去管它，我粘出来只是为了显得专业点嘛…</p>
<p>重点看这里<strong>监听目标元素与其祖先或视窗交叉状态的手段</strong>，其实就是观察一个元素是否在视窗可见。</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203027.webp" alt="是否可见"></p>
<p>可以看到，交叉了就是说明当前元素在视窗里，当前就是可见的了。</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203034.webp" alt="示意图"></p>
<ul>
<li><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserver">MDN IntersectionObserver</a></li>
<li><a target="_blank" rel="noopener" href="https://www.ruanyifeng.com/blog/2016/11/intersectionobserver_api.html">阮一峰 IntersectionObserver API 使用教程</a></li>
</ul>
<p><code>IntersectionObserver</code> 接口 (从属于<code>Intersection Observer API</code>) 提供了一种<strong>异步</strong>观察目标元素与其祖先元素或顶级文档视窗(<code>viewport</code>)交叉状态的方法。祖先元素与视窗(<code>viewport</code>)被称为根(<code>root</code>)。由于可见（visible）的本质是，目标元素与视口产生一个交叉区，所以这个 API 叫做”<strong>交叉观察器</strong>“。</p>
<p>简单点说就是<strong>它可以观察 root（默认是视口）和目标元素的交叉情况，当交叉率是 0% 或者 10% 或者更多的时候，可以触发指定的回调。</strong></p>
<p>当一个 <code>IntersectionObserver</code> 对象被创建时，其被配置为监听根中一段给定比例的可见区域。一旦 <code>IntersectionObserver</code> 被创建，则无法更改其配置，所以一个给定的观察者对象只能用来监听可见区域的特定变化值；然而，你可以在同一个观察者对象中配置监听多个目标元素。</p>
<h2 id="1-2-浏览器支持"><a href="#1-2-浏览器支持" class="headerlink" title="1.2 浏览器支持"></a>1.2 浏览器支持</h2><p>此时此刻，你也许想知道关于这项特性的浏览器支持情况。</p>
<p><a target="_blank" rel="noopener" href="https://caniuse.com/#search=IntersectionObserver">caniuse</a> 兼容性报告目前支持率是 90.12%，还不推荐用于大众化的场景中，但是它的能力和性能非常的好。</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203043.webp" alt="IntersectionObserver"></p>
<p>Intersection Observer 现在已被 <a target="_blank" rel="noopener" href="http://caniuse.com/#feat=intersectionobserver">Edge、Firefox、Chrome 和 Opera</a> 支持，这是一个好消息。</p>
<h1 id="2-IntersectionObserver的API"><a href="#2-IntersectionObserver的API" class="headerlink" title="2.IntersectionObserver的API"></a>2.IntersectionObserver的API</h1><h2 id="2-1-使用方法"><a href="#2-1-使用方法" class="headerlink" title="2.1 使用方法"></a>2.1 使用方法</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">var io &#x3D; new IntersectionObserver(callback, options)</span><br></pre></td></tr></table></figure>

<p>其实就是一个简单的构造函数。</p>
<p>以上代码会返回一个<code>IntersectionObserver</code>实例，<code>callback</code>是当元素的可见性变化时候的回调函数，<code>options</code>是一些配置项（可选）。</p>
<p>我们使用返回的这个实例来进行一些操作。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">io.observe(document.querySelector(&#39;img&#39;))  开始观察，接受一个DOM节点对象</span><br><span class="line">io.unobserve(element)   停止观察 接受一个element元素</span><br><span class="line">io.disconnect() 关闭观察器</span><br></pre></td></tr></table></figure>

<h2 id="2-2-optionsroot"><a href="#2-2-optionsroot" class="headerlink" title="2.2 optionsroot"></a>2.2 optionsroot</h2><p>options是一个对象，用来配置参数，也可以不填。共有三个属性，具体如下：</p>
<table>
<thead>
<tr>
<th>属性</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>root</td>
<td>所监听对象的具体祖先元素。如果未传入值或值为<code>null</code>，则默认使用顶级文档的视窗(一般为html)。</td>
</tr>
<tr>
<td>rootMargin</td>
<td>计算交叉时添加到<strong>根(root)边界盒<a target="_blank" rel="noopener" href="https://developer.mozilla.org/en-US/docs/Glossary/bounding_box">bounding box</a>的矩形偏移量， 可以有效的缩小或扩大根的判定范围从而满足计算需要。所有的偏移量均可用像素</strong>(<code>px</code>)或<strong>百分比</strong>(<code>%</code>)来表达, 默认值为”0px 0px 0px 0px”。</td>
</tr>
<tr>
<td>threshold</td>
<td>一个包含阈值的列表, 按升序排列, 列表中的每个阈值都是监听对象的交叉区域与边界区域的比率。当监听对象的任何阈值被越过时，都会触发callback。默认值为0。</td>
</tr>
</tbody></table>
<p>root用于观察的根元素，默认是浏览器的视口，也可以指定具体元素，指定元素的时候用于观察的元素必须是指定元素的子元素</p>
<p>threshold用来指定交叉比例，决定什么时候触发回调函数，是一个数组，默认是<code>[0]</code>。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">const options &#x3D; &#123;</span><br><span class="line">	root: null,</span><br><span class="line">	threshold: [0, 0.5, 1]</span><br><span class="line">&#125;</span><br><span class="line">var io &#x3D; new IntersectionObserver(callback, options)</span><br><span class="line">io.observe(document.querySelector(&#39;img&#39;))</span><br></pre></td></tr></table></figure>

<p>上面代码，我们指定了交叉比例为0，0.5，1，当观察元素img0%、50%、100%时候就会触发回调函数</p>
<p>rootMargin</p>
<p>用来扩大或者缩小视窗的的大小，使用css的定义方法，<code>10px 10px 30px 20px</code>表示top、right、bottom 和 left的值</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">const options &#x3D; &#123;</span><br><span class="line">	root: document.querySelector(&#39;.box&#39;),</span><br><span class="line">	threshold: [0, 0.5, 1],</span><br><span class="line">	rootMargin: &#39;30px 100px 20px&#39;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>为了方便理解，我画了张图，如下</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203055.webp" alt="options"></p>
<p>首先我们来看下图上的问题，蓝线是什么呢？他就是咱们定义的root元素，我们添加了<code>rootMargin</code>属性，将视窗的增大了，虚线就是现在的视窗，所以元素现在也就在视窗里面了。</p>
<p>由此可见，root元素只有在<code>rootMargin</code>为空的时候才是绝对的视窗。</p>
<p>说了简单的options，接下来我们看下<code>callback</code>。</p>
<h2 id="2-3-callback"><a href="#2-3-callback" class="headerlink" title="2.3 callback"></a>2.3 callback</h2><p>callback是添加监听后，当监听目标发生滚动变化时触发的回调函数。接收一个参数entries，即IntersectionObserverEntry实例。描述了目标元素与root的交叉状态。具体参数如下：</p>
<table>
<thead>
<tr>
<th>属性</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>boundingClientRect</td>
<td>返回包含目标元素的边界信息，返回结果与element.getBoundingClientRect() 相同</td>
</tr>
<tr>
<td><strong>intersectionRatio</strong></td>
<td>返回目标元素出现在可视区的比例</td>
</tr>
<tr>
<td>intersectionRect</td>
<td>用来描述root和目标元素的相交区域</td>
</tr>
<tr>
<td><strong>isIntersecting</strong></td>
<td>返回一个布尔值，下列两种操作均会触发callback：1. 如果目标元素出现在root可视区，返回true。2. 如果从root可视区消失，返回false</td>
</tr>
<tr>
<td>rootBounds</td>
<td>用来描述交叉区域观察者(intersection observer)中的根.</td>
</tr>
<tr>
<td>target</td>
<td>目标元素：与根出现相交区域改变的元素 (Element)</td>
</tr>
<tr>
<td>time</td>
<td>返回一个记录从 IntersectionObserver 的时间原点到交叉被触发的时间的时间戳</td>
</tr>
</tbody></table>
<p>表格中加粗的两个属性是比较常用的判断条件：<strong>isIntersecting</strong>和<strong>intersectionRatio</strong></p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203105.webp" alt="IntersectionObserverEntry打印的值"></p>
<p>上面我们说到，当元素的可见性变化时，就会触发callback函数。</p>
<p>callback函数会触发两次，元素进入视窗（开始可见时）和元素离开视窗（开始不可见时）都会触发</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">var io &#x3D; new IntersectionObserver((entries)&#x3D;&gt;&#123;</span><br><span class="line">	console.log(entries)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">io.observe($0)</span><br></pre></td></tr></table></figure>

<p>以上代码，请在chrome控制台进行调试，这里我使用了<code>$0</code>选择了上一次我审查元素的选择的节点</p>
<p>运行结果如下</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203114.webp" alt="运行结果"></p>
<p>我们可以看到callback函数有个<code>entries</code>参数，它是个<code>IntersectionObserverEntry</code>对象数组，</p>
<h2 id="2-4-方法"><a href="#2-4-方法" class="headerlink" title="2.4 方法"></a>2.4 方法</h2><p>介绍了这么多配置项及参数，差点忘了最重要的，IntersectionObserver有哪些方法？ 如果要监听某些元素，则必须要对该元素执行一下observe</p>
<table>
<thead>
<tr>
<th>方法</th>
<th>说明</th>
</tr>
</thead>
<tbody><tr>
<td>observe()</td>
<td>开始监听一个目标元素</td>
</tr>
<tr>
<td>unobserve()</td>
<td>停止监听特定目标元素</td>
</tr>
<tr>
<td>takeRecords()</td>
<td>返回所有观察目标的IntersectionObserverEntry对象数组</td>
</tr>
<tr>
<td>disconnect()</td>
<td>使IntersectionObserver对象停止全部监听工作</td>
</tr>
</tbody></table>
<p>接下来我们重点说下IntersectionObserverEntry对象</p>
<h2 id="2-5-IntersectionObserverEntry"><a href="#2-5-IntersectionObserverEntry" class="headerlink" title="2.5 IntersectionObserverEntry"></a>2.5 IntersectionObserverEntry</h2><p><code>IntersectionObserverEntry</code>提供观察元素的信息，有七个属性。</p>
<blockquote>
<p>boundingClientRect  目标元素的矩形信息</p>
<p>intersectionRatio   相交区域和目标元素的比例值   intersectionRect/boundingClientRect 不可见时小于等于0</p>
<p>intersectionRect    目标元素和视窗（根）相交的矩形信息 可以称为相交区域</p>
<p>isIntersecting      目标元素当前是否可见 Boolean值 可见为true</p>
<p>rootBounds              根元素的矩形信息，没有指定根元素就是当前视窗的矩形信息</p>
<p>target                      观察的目标元素</p>
<p>time                返回一个记录从<code>IntersectionObserver</code>的时间到交叉被触发的时间的时间戳</p>
</blockquote>
<p>上面几个矩形信息的关系如下</p>
<p><img data-src="https://cdn.jsdelivr.net/gh/huxingyi1997/my_img/img/20210418203122.webp" alt="关系"></p>
<p>👇 划重点</p>
<p><strong>intersectionRatio</strong>和<strong>isIntersecting</strong>是用来判断元素是否可见的，押题咯…</p>
<p>详细示例如下</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">    boundingClientRect: DOMRectReadOnly &#123;x: 8, y: 380, width: 300, height: 300, top: 380, …&#125;</span><br><span class="line">    intersectionRatio: 0.023333333432674408</span><br><span class="line">    intersectionRect: DOMRectReadOnly &#123;x: 8, y: 380, width: 300, height: 7, top: 380, …&#125;</span><br><span class="line">    isIntersecting: true</span><br><span class="line">    rootBounds: DOMRectReadOnly &#123;x: 0, y: 0, width: 1903, height: 387, top: 0, …&#125;</span><br><span class="line">    target: img.lazy</span><br><span class="line">    time: 440149.8099999735</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>IntersectionObserverEntry上述示例的每项详细配置如下</p>
<ul>
<li><code>time</code>：可见性发生变化的时间，是一个高精度时间戳，单位为毫秒，返回一个记录从 <code>IntersectionObserver</code> 的时间原点(time origin)到交叉被触发的时间的时间戳(DOMHighResTimeStamp)，图中为440149.8099999735</li>
<li><code>target</code>：被观察的目标元素，是一个 DOM 节点对象，选择了图像img中的.lazy类型元素</li>
<li><code>rootBounds</code>：根元素的矩形区域的信息，<code>getBoundingClientRect()</code> 方法的返回值，如果没有根元素（即直接相对于视口滚动），则返回 <code>null</code></li>
<li><code>boundingClientRect</code>：目标元素的矩形区域的信息</li>
<li><code>intersectionRect</code>：目标元素与视口（或根元素）的交叉区域的信息</li>
<li><code>intersectionRatio</code>：目标元素的可见比例，即 <code>intersectionRect</code> 占 <code>boundingClientRect</code> 的比例，完全可见时为 1，完全不可见时小于等于0</li>
<li><a target="_blank" rel="noopener" href="https://developer.mozilla.org/zh-CN/docs/Web/API/IntersectionObserverEntry/isIntersecting"><code>isIntersecting</code></a> 是否交叉，交叉为true</li>
</ul>
<h2 id="2-6-配置"><a href="#2-6-配置" class="headerlink" title="2.6 配置"></a>2.6 配置</h2><p><code>observerConfig.root</code> 所监听对象的具体祖先元素(element)。如果未传入值或值为 <code>null</code>，则默认使用顶级文档的视窗。</p>
<p><code>observerConfig.rootMargin</code> 计算交叉时添加到根(<code>root</code>)边界盒 bounding box 的矩形偏移量， 可以有效的缩小或扩大根的判定范围从而满足计算需要。所有的偏移量均可用像素(pixel)(px)或百分比(percentage)(%)来表达, 默认值为”<code>0px 0px 0px 0px</code>“，用法和普通的 <code>margin</code> 一样（top、right、bottom、left）。</p>
<p><code>observerConfig.threshold</code> <strong>注意 MDN 文档中的 <code>thresholds</code> 是错误的</strong>，一个包含阈值的列表, 按升序排列, 列表中的每个阈值都是监听对象的交叉区域与边界区域的比率。当监听对象的任何阈值被越过时，都会生成一个通知(Notification)。如果构造器未传入值, 则默认值为0，也可以是 <code>[0, 0.25, 0.5, 0.75, 1]</code>。</p>
<h1 id="3-实际应用"><a href="#3-实际应用" class="headerlink" title="3.实际应用"></a>3.实际应用</h1><p>通过上面一些概念我们大概了解了<code>IntersectionObserver</code>是个什么东西，接下来我们用它来写点代码，投入实战。</p>
<h2 id="3-1-图片懒加载"><a href="#3-1-图片懒加载" class="headerlink" title="3.1 图片懒加载"></a>3.1 图片懒加载</h2><p>第一个应用写什么呢？没错就是懒加载。</p>
<p>通过IntersectionObserver来实现懒加载，我们只需要设置回调，判断当前元素是否可见，再进行渲染操作就行了，而不用去关心内部的计算，相比于常规方案大大提高了开发效率。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">const imgList &#x3D; [...document.querySelectorAll(&#39;img&#39;)];</span><br><span class="line"></span><br><span class="line">var io &#x3D; new IntersectionObserver((entries) &#x3D;&gt; &#123;</span><br><span class="line">    entries.forEach(item &#x3D;&gt; &#123;</span><br><span class="line">        &#x2F;&#x2F; isIntersecting是一个Boolean值，判断目标元素当前是否可见</span><br><span class="line">        if (item.isIntersecting) &#123;</span><br><span class="line">            item.target.src &#x3D; item.target.dataset.src;</span><br><span class="line">            &#x2F;&#x2F; 图片加载后即停止监听该元素</span><br><span class="line">            io.unobserve(item.target);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;, &#123;</span><br><span class="line">	root: document.querySelector(&#39;.root&#39;);</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; observe遍历监听所有img节点</span><br><span class="line">imgList.forEach(img &#x3D;&gt; io.observe(img));</span><br></pre></td></tr></table></figure>

<h2 id="3-2-埋点曝光"><a href="#3-2-埋点曝光" class="headerlink" title="3.2 埋点曝光"></a>3.2 埋点曝光</h2><p>假如有个需求，对一个页面中的特定元素，只有在其完全显示在可视区内时进行埋点曝光。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line">const boxList &#x3D; [...document.querySelectorAll(&#39;.box&#39;)];</span><br><span class="line"></span><br><span class="line">var io &#x3D; new IntersectionObserver((entries) &#x3D;&gt; &#123;</span><br><span class="line">    entries.forEach(item &#x3D;&gt; &#123;</span><br><span class="line">        &#x2F;&#x2F; intersectionRatio &#x3D;&#x3D;&#x3D; 1说明该元素完全暴露出来，符合业务需求</span><br><span class="line">        if (item.intersectionRatio &#x3D;&#x3D;&#x3D; 1) &#123;</span><br><span class="line">            &#x2F;&#x2F; ... 埋点曝光代码</span><br><span class="line">            io.unobserve(item.target)</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;)</span><br><span class="line">&#125;, &#123;</span><br><span class="line">    root: null,</span><br><span class="line">    threshold: 1, &#x2F;&#x2F; 阀值设为1，当只有比例达到1时才触发回调函数</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line">&#x2F;&#x2F; observe遍历监听所有box节点</span><br><span class="line">boxList.forEach(box &#x3D;&gt; io.observe(box))</span><br></pre></td></tr></table></figure>

<p><strong>总之，这是一个相当方便好用的API！</strong></p>

    </div>

    
    
    
      
<div>
        <div style="text-align:center;color: #ccc;font-size:14px;">-------------本文结束<i class="fa fa-paw"></i>感谢您的阅读-------------</div>
</div>
        

  <div class="followme">
    <p>欢迎关注我的其它发布渠道</p>

    <div class="social-list">

        <div class="social-item">
          <a target="_blank" class="social-link" href="/atom.xml">
            <span class="icon">
              <i class="fa fa-rss"></i>
            </span>

            <span class="label">RSS</span>
          </a>
        </div>
    </div>
  </div>


      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/JavaScript/" rel="tag"><i class="fa fa-tag"></i> JavaScript</a>
              <a href="/tags/%E6%87%92%E5%8A%A0%E8%BD%BD/" rel="tag"><i class="fa fa-tag"></i> 懒加载</a>
              <a href="/tags/IntersectionObserver/" rel="tag"><i class="fa fa-tag"></i> IntersectionObserver</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2021/03/29/ES2021(ES12)%E6%96%B0%E5%8A%9F%E8%83%BD/" rel="prev" title="ES2021(ES12)">
      <i class="fa fa-chevron-left"></i> ES2021(ES12)
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/04/03/JavaScript%E6%89%8B%E5%86%99%E6%95%B0%E7%BB%84%E5%B8%B8%E7%94%A8%E5%87%BD%E6%95%B0/" rel="next" title="JavaScript手写数组常用函数">
      JavaScript手写数组常用函数 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          
    <div class="comments" id="valine-comments"></div>

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#1-IntersectionObserver%E6%98%AF%E4%BB%80%E4%B9%88"><span class="nav-text">1.IntersectionObserver是什么</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-1-%E6%A6%82%E5%BF%B5"><span class="nav-text">1.1 概念</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#1-2-%E6%B5%8F%E8%A7%88%E5%99%A8%E6%94%AF%E6%8C%81"><span class="nav-text">1.2 浏览器支持</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-IntersectionObserver%E7%9A%84API"><span class="nav-text">2.IntersectionObserver的API</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#2-1-%E4%BD%BF%E7%94%A8%E6%96%B9%E6%B3%95"><span class="nav-text">2.1 使用方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-2-optionsroot"><span class="nav-text">2.2 optionsroot</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-3-callback"><span class="nav-text">2.3 callback</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-4-%E6%96%B9%E6%B3%95"><span class="nav-text">2.4 方法</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-5-IntersectionObserverEntry"><span class="nav-text">2.5 IntersectionObserverEntry</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-6-%E9%85%8D%E7%BD%AE"><span class="nav-text">2.6 配置</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-%E5%AE%9E%E9%99%85%E5%BA%94%E7%94%A8"><span class="nav-text">3.实际应用</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#3-1-%E5%9B%BE%E7%89%87%E6%87%92%E5%8A%A0%E8%BD%BD"><span class="nav-text">3.1 图片懒加载</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-2-%E5%9F%8B%E7%82%B9%E6%9B%9D%E5%85%89"><span class="nav-text">3.2 埋点曝光</span></a></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="hxy"
      src="/images/Robben.gif">
  <p class="site-author-name" itemprop="name">hxy</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">80</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">120</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/huxingyi1997" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;huxingyi1997" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="mailto:huxingyi1997@zju.edu.cn" title="E-Mail → mailto:huxingyi1997@zju.edu.cn" rel="noopener" target="_blank"><i class="fa fa-envelope fa-fw"></i>E-Mail</a>
      </span>
  </div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2022</span>
  <span class="with-love">
    <i class="fa fa-frog"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">hxy</span>
</div>

<div class="theme-info">
  <div class="powered-by"></div>
  <span class="post-count">博客全站共1039.2k字</span>
</div>

        
<div class="busuanzi-count">
  <script async src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script>
    <span class="post-meta-item" id="busuanzi_container_site_uv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-user"></i>
      </span>
      <span class="site-uv" title="总访客量">
        <span id="busuanzi_value_site_uv"></span>
      </span>
    </span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item" id="busuanzi_container_site_pv" style="display: none;">
      <span class="post-meta-item-icon">
        <i class="fa fa-eye"></i>
      </span>
      <span class="site-pv" title="总访问量">
        <span id="busuanzi_value_site_pv"></span>
      </span>
    </span>
</div>








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="//cdn.jsdelivr.net/npm/lozad@1/dist/lozad.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  




  
<script src="/js/local-search.js"></script>













  

  


<script>
NexT.utils.loadComments(document.querySelector('#valine-comments'), () => {
  NexT.utils.getScript('//unpkg.com/valine/dist/Valine.min.js', () => {
    var GUEST = ['nick', 'mail', 'link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item => {
      return GUEST.includes(item);
    });
    new Valine({
      el         : '#valine-comments',
      verify     : false,
      notify     : true,
      appId      : 'pQsO3ySbU4VtWN2j1FLA74Ha-gzGzoHsz',
      appKey     : 'QYacMDY2VY7Wazprg1X6FiUv',
      placeholder: "Just go go",
      avatar     : 'mm',
      meta       : guest,
      pageSize   : '10' || 10,
      visitor    : false,
      lang       : 'zh-cn' || 'zh-cn',
      path       : location.pathname,
      recordIP   : false,
      serverURLs : ''
    });
  }, window.Valine);
});
</script>

  
  <!-- 动态背景特效 -->
  <!-- 樱花特效 -->
    <script async src="/js/src/sakura.js"></script>
    <script async src="/js/src/fairyDustCursor.js"></script>
</body>
</html>
